package Test;

/**
 * @author Kevin
 * @date 2020/3/1 11:17
 */
public class Heap {
    private int[] a;
    private int n;
    private int count;

    public Heap(int capacity) {
        a = new int[capacity + 1];
        n = capacity;
        count = 0;
    }

    public void insert(int data) {
        if (count >= n) return;
        ++count;
        a[count] = data;
        int i = count;
        while((i-1)/2 > 0 && a[i] > a[(i-1)/2]) {
            swap(a,i,(i-1)/2);
            i = (i-1)/2;
        }
    }

    public void removeMax() {
        if (count == 0) return;
        a[0] = a[count];
        heapify(a, count, 0);
    }

    public void heapify(int[] a, int n, int i) {
        while (true) {
            int maxPos = i;
            if (i * 2 + 1 <= n && a[i * 2 + 1] > a[i]) maxPos = i * 2 + 1;
            if (i * 2 + 2 <= n && a[i * 2 + 2] > a[maxPos]) maxPos = i * 2 + 2;
            if (maxPos == i) {
                break;
            }
            swap(a, i, maxPos);
            i = maxPos;
        }
    }


    public void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
